package cn.tedu.apps_system.service.impl;

import cn.tedu.apps_system.base.response.JsonResult;
import cn.tedu.apps_system.base.response.ResultCode;
import cn.tedu.apps_system.mapper.UserMapper;
import cn.tedu.apps_system.pojo.dto.LoginTime;
import cn.tedu.apps_system.pojo.dto.UserLoginDto;
import cn.tedu.apps_system.pojo.dto.UserRegDto;
import cn.tedu.apps_system.pojo.entity.User;
import cn.tedu.apps_system.pojo.vo.UserVO;
import cn.tedu.apps_system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public JsonResult registerUser(UserRegDto userRegDto) {
        log.debug("userRegDto: "+userRegDto);
        if(userMapper.existsByUsername(userRegDto.getUsername())>0){
            return new JsonResult(ResultCode.USERNAME_EXIST);
        }

        User user = new User();
        BeanUtils.copyProperties(userRegDto, user);
        user.setStatus(1);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        int n = userMapper.reg(user);
        if(n>0){
            return JsonResult.ok();
        }
        return new JsonResult(ResultCode.FAILED);
    }

    @Override
    public JsonResult loginUser(UserLoginDto userLoginDto, HttpSession session) {
        log.debug("userLoginDto: "+userLoginDto);
        UserVO userVO = userMapper.login(userLoginDto);
        if (userVO==null){
            return new JsonResult(ResultCode.LOGIN_FAILED);
        }
        //记录登录时间
        LoginTime loginTime = new LoginTime();
        loginTime.setUsername(userVO.getUsername());
        loginTime.setLastLoginTime(new Date());
        userMapper.loginTime(loginTime);
        session.setAttribute("user",userVO);
        return JsonResult.ok(userVO);
    }

    @Override
    public JsonResult reviseUser(UserRegDto userRegDto, HttpSession session) {
        log.debug("userRegDto: "+userRegDto);
        UserVO userVO = (UserVO)session.getAttribute("user");
        if(userVO==null){
            return new JsonResult(ResultCode.UNAUTHORIZED);
        }

        User user = new User();
        BeanUtils.copyProperties(userRegDto, user);
        user.setUsername(userVO.getUsername());
        user.setUpdateTime(new Date());
        int n = userMapper.revise(user);
        if(n>0){
            return JsonResult.ok();
        }
        return new JsonResult(ResultCode.FAILED);
    }

    @Override
    public JsonResult logoutUser(HttpSession session) {
        session.removeAttribute("user");
        return JsonResult.ok();
    }
}
